#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
HackerPermKeeper 版本信息模块
提供版本号、发布信息和兼容性检查功能
"""

import sys
from datetime import datetime
from typing import Tuple, Dict, Any

# 版本信息
__version__ = "7.1.0"
__version_info__ = (7, 1, 0)
__release_date__ = "2024-10-11"
__status__ = "stable"  # alpha, beta, rc, stable
__build_number__ = "20241011001"

# 项目信息
__project_name__ = "HackerPermKeeper"
__project_description__ = "终极持久化测试器 - 跨平台权限维持工具"
__author__ = "HackerPermKeeper开发团队"
__license__ = "MIT"
__homepage__ = "https://github.com/hackerPermKeeper/ultimate-persistence-tester"

# 兼容性信息
MINIMUM_PYTHON_VERSION = (3, 6, 0)
SUPPORTED_PLATFORMS = ["linux", "windows", "darwin"]
SUPPORTED_ARCHITECTURES = ["x86_64", "amd64", "arm64"]

# 功能特性版本
FEATURES_VERSION = {
    "linux_persistence": "7.0.0",
    "windows_persistence": "7.1.0", 
    "parallel_execution": "7.1.0",
    "dry_run_mode": "7.0.0",
    "config_file_support": "7.0.0",
    "auto_cleanup": "7.0.0",
    "state_management": "7.0.0",
    "cross_platform": "7.1.0"
}

# API版本
API_VERSION = "1.0"
CONFIG_VERSION = "1.0"


def get_version() -> str:
    """获取版本号字符串"""
    return __version__


def get_version_info() -> Tuple[int, int, int]:
    """获取版本号元组"""
    return __version_info__


def get_full_version() -> str:
    """获取完整版本信息"""
    if __status__ == "stable":
        return f"v{__version__}"
    else:
        return f"v{__version__}-{__status__}"


def get_build_info() -> Dict[str, Any]:
    """获取构建信息"""
    return {
        "version": __version__,
        "version_info": __version_info__,
        "release_date": __release_date__,
        "status": __status__,
        "build_number": __build_number__,
        "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
        "platform": sys.platform,
        "architecture": sys.maxsize > 2**32 and "64bit" or "32bit"
    }


def check_python_compatibility() -> bool:
    """检查Python版本兼容性"""
    current_version = sys.version_info[:3]
    return current_version >= MINIMUM_PYTHON_VERSION


def check_platform_support(platform: str = None) -> bool:
    """检查平台支持"""
    if platform is None:
        platform = sys.platform
    
    # 标准化平台名称
    platform_map = {
        "win32": "windows",
        "linux": "linux", 
        "linux2": "linux",
        "darwin": "darwin"
    }
    
    normalized_platform = platform_map.get(platform, platform)
    return normalized_platform in SUPPORTED_PLATFORMS


def get_feature_version(feature: str) -> str:
    """获取特定功能的版本"""
    return FEATURES_VERSION.get(feature, "未知")


def is_feature_available(feature: str, required_version: str = None) -> bool:
    """检查功能是否可用"""
    if feature not in FEATURES_VERSION:
        return False
    
    if required_version is None:
        return True
    
    feature_version = FEATURES_VERSION[feature]
    return _compare_versions(feature_version, required_version) >= 0


def _compare_versions(version1: str, version2: str) -> int:
    """比较版本号
    返回值: 1 (version1 > version2), 0 (相等), -1 (version1 < version2)
    """
    def normalize_version(v):
        return [int(x) for x in v.split('.')]
    
    v1_parts = normalize_version(version1)
    v2_parts = normalize_version(version2)
    
    # 补齐长度
    max_len = max(len(v1_parts), len(v2_parts))
    v1_parts.extend([0] * (max_len - len(v1_parts)))
    v2_parts.extend([0] * (max_len - len(v2_parts)))
    
    for i in range(max_len):
        if v1_parts[i] > v2_parts[i]:
            return 1
        elif v1_parts[i] < v2_parts[i]:
            return -1
    
    return 0


def print_version_info():
    """打印详细版本信息"""
    print(f"{__project_name__} {get_full_version()}")
    print(f"发布日期: {__release_date__}")
    print(f"状态: {__status__}")
    print(f"构建号: {__build_number__}")
    print(f"Python版本: {sys.version}")
    print(f"平台: {sys.platform}")
    print(f"架构: {sys.maxsize > 2**32 and '64位' or '32位'}")
    print()
    print("支持的功能:")
    for feature, version in FEATURES_VERSION.items():
        print(f"  - {feature}: v{version}")


def get_changelog_entry() -> str:
    """获取当前版本的变更日志条目"""
    return f"""
## [v{__version__}] - {__release_date__}

### 🆕 新功能
- Windows平台持久化机制支持
- 并行执行功能
- 跨平台兼容性

### 🔧 修复
- Logger初始化问题
- 属性初始化错误
- 编码兼容性问题

### 🔄 改进
- 参数解析增强
- 测试框架完善
- 错误处理优化
"""


def validate_environment() -> Dict[str, bool]:
    """验证运行环境"""
    results = {
        "python_compatible": check_python_compatibility(),
        "platform_supported": check_platform_support(),
        "all_features_available": True
    }
    
    # 检查所有功能是否可用
    for feature in FEATURES_VERSION:
        if not is_feature_available(feature):
            results["all_features_available"] = False
            break
    
    return results


if __name__ == "__main__":
    # 命令行调用时显示版本信息
    import argparse
    
    parser = argparse.ArgumentParser(description="版本信息工具")
    parser.add_argument("--version", action="store_true", help="显示版本号")
    parser.add_argument("--full", action="store_true", help="显示完整版本信息")
    parser.add_argument("--build", action="store_true", help="显示构建信息")
    parser.add_argument("--check", action="store_true", help="检查环境兼容性")
    parser.add_argument("--changelog", action="store_true", help="显示变更日志条目")
    
    args = parser.parse_args()
    
    if args.version:
        print(get_version())
    elif args.full:
        print_version_info()
    elif args.build:
        import json
        print(json.dumps(get_build_info(), indent=2, ensure_ascii=False))
    elif args.check:
        results = validate_environment()
        print("环境兼容性检查:")
        for check, result in results.items():
            status = "✓" if result else "✗"
            print(f"  {status} {check}: {'通过' if result else '失败'}")
    elif args.changelog:
        print(get_changelog_entry())
    else:
        print(f"{__project_name__} v{__version__}")
        print("使用 --help 查看更多选项")